{extend name="public/common"}

{block name="style"}
<title>请假审批</title>
<link rel="stylesheet" href="/home/css/approval/add.css?v={$Think.config.version}">
{/block}

{block name="body"}
<div id="app" v-cloak>
    <div class="type-title">请假审批</div>
    <div class="form" id="dayoff">
        <ul>
            <li>
                <p>类型：</p>
                <div class="box">请假申请</div>
            </li>
            <li>
                <p>假别：</p>
                <div @click="toggleType" :class="typeOfLeave.nowType.id == 0 ? 'special box' : 'box'">{{typeOfLeave.nowType.name}}
                    <span class="available-day" v-if="typeOfLeave.nowType.id != 0 && typeOfLeave.nowType.is_show_total_days != 0 ">可用天数：{{availableDay}}</span>
                </div>
                <mt-popup  position="bottom"  v-model="typeOfLeave.popupVisible" class="mint-popup">
                    <div class="picker-toolbar">
                        <span class="mint-datetime-action mint-datetime-cancel" @click="toggleType">取消</span>
                        <span class="mint-datetime-action mint-datetime-confirm" @click="typeConfirm">确定</span>
                    </div>
                    <div class="picker-day">已用天数：{{typeOfLeave.onChangeType.used_days}} {{typeOfLeave.onChangeType.is_show_total_days!= 0 ? `| 总天数：${typeOfLeave.onChangeType.total_days}` : ''}}</div>
                    <mt-picker :slots="typeOfLeave.slots" value-key="name" @change="selectType"></mt-picker>
                </mt-popup>
            </li>
            <li>
                <p>时长（天）：</p>
                <div @click="toggleDuring" :class="during.nowType.id == 0 ? 'special box' : 'box'">{{during.nowType.name}}</div>
                <mt-popup  position="bottom"  v-model="during.popupVisible" class="mint-popup">
                    <div class="picker-toolbar">
                        <span class="mint-datetime-action mint-datetime-cancel" @click="toggleDuring">取消</span>
                        <span class="mint-datetime-action mint-datetime-confirm" @click="duringConfirm">确定</span>
                    </div>
                    <div class="picker-day special-day"></div>
                    <mt-picker :slots="during.slots" value-key="name" @change="selectDuring"></mt-picker>
                </mt-popup>
            </li>
            <li>
                <p>开始时间：</p>
                <div @click="chooseStartTime" v-if="typeof startTime === 'number'" class="box">{{startTime | timeToString('ymdhi')}}</div>
                <div @click="chooseStartTime" v-else class="special box">{{startTime}}</div>
                <mt-datetime-picker
                        v-model="start_time"
                        type="datetime"
                        ref="timePicker_1"
                        year-format="{value} 年"
                        month-format="{value} 月"
                        date-format="{value} 日"
                        hour-format="{value} 时"
                        minute-format="{value} 分"
                        :start-date="nowTime"
                        :end-date="temp_time"
                        @confirm="startTimeConfirm">
                </mt-datetime-picker>
            </li>
            <li>
                <p>结束时间：</p>
                <div @click="chooseEndTime" v-if="typeof endTime === 'number'" class="box">{{endTime | timeToString('ymdhi')}}</div>
                <div @click="chooseEndTime" v-else class="special box">{{endTime}}</div>
                <mt-datetime-picker
                        v-model="end_time"
                        type="datetime"
                        ref="timePicker_2"
                        year-format="{value} 年"
                        month-format="{value} 月"
                        date-format="{value} 日"
                        hour-format="{value} 时"
                        minute-format="{value} 分"
                        :start-date="start_time"
                        @confirm="endTimeConfirm">
                </mt-datetime-picker>
            </li>
            <li>
                <p>职位代理人：</p>
                <input type="text" v-model="agent" placeholder="请输入职位代理人">
            </li>
            <li>
                <p>审批人：</p>
                <div @click="toggleApprover" :class="approver.nowType.userid == 0 ? 'special box' : 'box'">{{approver.nowType.username}}</div>
                <mt-popup  position="bottom"  v-model="approver.popupVisible" class="mint-popup">
                    <div class="picker-toolbar">
                        <span class="mint-datetime-action mint-datetime-cancel" @click="toggleApprover">取消</span>
                        <span class="mint-datetime-action mint-datetime-confirm" @click="approverConfirm">确定</span>
                    </div>
                    <div class="picker-day special-day"></div>
                    <mt-picker :slots="approver.slots" value-key="username" @change="selectApprover" ref="picker"></mt-picker>
                </mt-popup>
            </li>
            <li>
                <p>备注：</p>
                <div class="textarea">
                    <textarea type="text" v-model="remark" placeholder="请输入备注" oninput="if(value.length>200)value=value.slice(0,200);"></textarea>
                    <span>{{remark.length}} / 200字</span>
                </div>
            </li>
        </ul>
    </div>
    <div class="foot">
        <div class="cancel" @click="cancel">取消</div>
        <div class="confirm" @click="subimtAjax">确定</div>
    </div>
</div>
{/block}

{block name="script"}
<script>
    console.log({$approval_user})
    console.log({$leave_list})
    var vw = new Vue({
        el: "#app",
        data: {
            type: 1,
            startTime: '请选择开始时间',
            endTime: '请选择结束时间',
            availableDay: 0,
            start_time: new Date(),
            temp_time: new Date(new Date().getTime() + 365*24*3600*1000),
            end_time: new Date(),
            nowTime: new Date(),
            during: {
                slots: [
                    {
                        values: [],
                        defaultIndex: 1
                    }
                ],
                nowType: {
                    name: '请选择时长',
                    id: 0
                },
                onChangeType: {
                    name: '请选择时长',
                    id: 0
                },
                popupVisible:false
            },
            agent: '',
            typeOfLeave: {
                slots: [
                    {
                        values: {$leave_list},
                        defaultIndex: 1
                    }
                ],
                nowType: {
                    name: '请选择假别',
                    id: 0
                },
                onChangeType: {
                    name: '请选择假别',
                    id: 0
                },
                popupVisible:false
            },
            approver: {
                slots: [
                    {
                        values: {$approval_user},
                        defaultIndex: 1
                    }
                ],
                nowType: {
                    username: '请选择审批人',
                    userid: 0
                },
                onChangeType: {
                    username: '请选择审批人',
                    userid: 0
                },
                popupVisible: false
            },
            remark: '',
            id:0,
            approvalUser: [],
            permission: {$permission},
            clickLoading: true,
            showDays: 0
        },
        created() {

            if(window.location.href.indexOf('id') > -1) {
                var hrefs = window.location.href.split("/"),
                    ids = hrefs[hrefs.length - 1].split("."),
                    _this = this;
                _this.id = ids[0];
                _this.$indicator.open({
                    text: '正在获取中',
                    spinnerType: 'triple-bounce'
                });
                _this.$http.post('{:Url("Approval/getDetail")}',{
                    'id': _this.id,
                    'class': _this.type
                },{emulateJSON:true}).then(function (res) {
                    var data = res.body;
                    console.log(data)
                    _this.$indicator.close();
                    if(data.code == 1){
                        _this.startTime = data.data.start_time;
                        _this.endTime = data.data.end_time;
                        _this.remark = data.data.content;
                        _this.agent = data.data.agent;
                        Object.assign(_this.approvalUser,data.data.approval_user);
                        _this.typeOfLeave.nowType = _this.typeOfLeave.slots[0].values[data.data.type - 1];
                        _this.availableDay = _this.typeOfLeave.nowType.total_days - _this.typeOfLeave.nowType.used_days;
                        if(_this.typeOfLeave.nowType.is_show_total_days !=0) {
                            _this.showDays = _this.availableDay;
                            this.during.slots[0].values = [...Array(_this.showDays*2)].map((v, k) => {
                                return {
                                    'name': k/2 + 0.5,
                                    'id': v
                                }
                            });
                        } else if(_this.showDays != _this.typeOfLeave.nowType.total_days) {
                            _this.showDays = _this.typeOfLeave.nowType.total_days;
                            this.during.slots[0].values = [...Array(_this.showDays*2)].map((v, k) => {
                                return {
                                    'name': k/2 + 0.5,
                                    'id': v
                                }
                            });
                        }
                        _this.during.nowType = _this.during.slots[0].values[(Number(data.data.duration) / .5) - 1];
                        // _this.during.nowType.name = data.data.duration;
                        // _this.during.nowType.id = parseInt(data.data.type) / .5;
                        // _this.typeOfLeave.nowType.id = data.data.type;
                        // _this.typeOfLeave.nowType.name = data.data.type_text;
                        _this.approver.nowType.userid = data.data.apply_user == data.data.approval_user[0].approval_user?data.data.approval_user[1].approval_user:data.data.approval_user[0].approval_user;
                        _this.approver.nowType.username = data.data.apply_user == data.data.approval_user[0].approval_user?data.data.approval_user[1].username:data.data.approval_user[0].username;
                        _this.$nextTick(function() {
                            setTimeout(function() {
                                _this.typeOfLeave.slots[0].defaultIndex = data.data.type - 1;
                                _this.approver.slots[0].defaultIndex = 0;
                                _this.during.slots[0].defaultIndex = (Number(data.data.duration) / .5) - 1;
                            }, 100);
                        });
                    }else{
                        _this.$toast({
                            message: data.msg,
                            duration: 1500
                        });
                    }
                }, function (res) {
                    _this.$indicator.close();
                    _this.$toast({
                        message: "获取失败，请重试！",
                        duration: 1500
                    });
                });
            }

        },
        mounted() {
            var _this = this;
            if(window.location.href.indexOf('id') == -1) {
                _this.$nextTick(function() {
                    setTimeout(function() {
                        _this.typeOfLeave.slots[0].defaultIndex = 0;
                        _this.approver.slots[0].defaultIndex = 0;
                        _this.during.slots[0].defaultIndex = 0;
                    }, 100);
                });
            }
        },
        methods: {
            chooseStartTime() {
                this.$refs.timePicker_1.open();
            },
            chooseEndTime() {
                if(typeof this.startTime != 'number') {
                    this.$toast({
                        message:"请先选择开始时间",
                        duration:1500
                    });
                    return false;
                }
                this.$refs.timePicker_2.open();
            },
            toggleDuring(){
                var _this = this;
                if(_this.typeOfLeave.nowType.id == 0) {
                    _this.$toast({
                        message:"请先选择假别",
                        duration:1500
                    });
                    return false;
                } else {

                }
                _this.during.popupVisible = !_this.during.popupVisible;
            },
            duringConfirm(){
                var _this = this;
                if(_this.typeOfLeave.nowType.is_show_total_days !=0 && _this.during.onChangeType.name > _this.availableDay){
                    _this.$toast({
                        message:`该类型假期只有${_this.availableDay}天`,
                        duration:1500
                    });
                    return false;
                }
                _this.$http.post('{:Url("Approval/check_user_apply")}', {
                    'leave_id': _this.typeOfLeave.nowType.id,
                    'select_days': _this.during.onChangeType.name
                },{emulateJSON:true}).then(function (res) {
                    var data = res.data;
                    if(data.code == 0) {
                        _this.$toast({
                            message: data.msg,
                            duration: 2000
                        });
                    }
                    if(_this.during.nowType != _this.during.onChangeType){
                        _this.during.nowType = _this.during.onChangeType;
                    }
                    _this.during.popupVisible = !_this.during.popupVisible;
                },function (res) {
                    _this.$toast({
                        message: '网络错误，请重试',
                        duration: 1500
                    });
                    return false;
                });
            },
            selectDuring(p,v){
                var _this = this;
                if(v[0]){
                    _this.during.onChangeType = v[0];
                }
            },
            toggleType(){
                var _this = this;
                _this.typeOfLeave.popupVisible = !_this.typeOfLeave.popupVisible;
            },
            typeConfirm(){
                var _this = this;
                if(_this.typeOfLeave.onChangeType.is_show_total_days !=0 && _this.typeOfLeave.onChangeType.total_days <=_this.typeOfLeave.onChangeType.used_days){
                    _this.$toast({
                        message:"该类型假期已用完",
                        duration:1500
                    });
                    return false;
                }
                if(_this.typeOfLeave.nowType != _this.typeOfLeave.onChangeType){
                    _this.typeOfLeave.nowType = _this.typeOfLeave.onChangeType;
                    if(_this.typeOfLeave.onChangeType.is_show_total_days !=0) {
                        _this.availableDay = _this.typeOfLeave.nowType.total_days - _this.typeOfLeave.nowType.used_days;
                        _this.showDays = _this.availableDay;
                        this.during.slots[0].values = [...Array(_this.showDays*2)].map((v, k) => {
                            return {
                                'name': k/2 + 0.5,
                                'id': v
                            }
                        });
                    } else if(_this.showDays != _this.typeOfLeave.nowType.total_days) {
                        _this.showDays = _this.typeOfLeave.nowType.total_days;
                        this.during.slots[0].values = [...Array(_this.showDays*2)].map((v, k) => {
                            return {
                                'name': k/2 + 0.5,
                                'id': v
                            }
                        });
                    }
                }
                _this.typeOfLeave.popupVisible = !_this.typeOfLeave.popupVisible;

                // 独生子女假和育儿假的特殊提示
                _this.showLeaveTypeNotice();
            },
            showLeaveTypeNotice(){
                var _this = this;
                var leaveId = _this.typeOfLeave.nowType.id;
                var noticeMessage = '';

                // 独生子女假 id=11
                if(leaveId == 11){
                    noticeMessage = '根据《浙江省人口与计划生育条例》规定,浙江省独生子女在其父母一方年满60周岁后,每年可享受5天陪护父母假。若经核实不符合此假期条件,按事假计算。';
                }
                // 育儿假 id=12
                else if(leaveId == 12){
                    noticeMessage = '根据《浙江省人口与计划生育条例》规定,在子女三周岁内,夫妻双方每年各享受10天育儿假,育儿假从子女出生之日起按照周年计算。若经核实不符合此假期条件,按事假计算。';
                }

                // 如果有提示信息,显示弹窗
                if(noticeMessage){
                    _this.$messagebox({
                        title: '假期提示',
                        message: '<div style="padding: 15px 20px; text-align: center; line-height: 1.6; font-size: 14px;">' + noticeMessage + '</div>',
                        confirmButtonText: '我知道了',
                        dangerouslyUseHTMLString: true
                    });
                }
            },
            selectType(p,v){
                var _this = this;
                if(v[0]){
                    _this.typeOfLeave.onChangeType = v[0];
                }
            },
            toggleApprover(){
                var _this = this;
                _this.approver.popupVisible = !_this.approver.popupVisible;
            },
            approverConfirm(){
                var _this = this;
                console.log(_this.approvalUser)
                if(_this.approver.nowType != _this.approver.onChangeType){
                    _this.approver.nowType = _this.approver.onChangeType;
                    if(_this.id != 0) {
                        _this.approvalUser[0].username = _this.approver.nowType.username;
                        _this.approvalUser[0].approval_user = _this.approver.nowType.userid;
                    }
                }
                _this.approver.popupVisible = !_this.approver.popupVisible;
            },
            selectApprover(p,v){
                var _this = this;
                if(v[0]){
                    _this.approver.onChangeType = v[0];
                }
            },
            startTimeConfirm(val) {
                if(new Date(val).getTime() / 1000 > this.endTime){
                    this.$toast({
                        message:"开始时间应早于结束时间",
                        duration:1500
                    });
                    return false;
                }
                this.start_time = val;
                this.startTime = new Date(this.start_time).getTime() / 1000;
            },
            endTimeConfirm(val) {
                this.end_time = val;
                this.endTime = new Date(this.end_time).getTime() / 1000;
            },
            cancel(){
                window.history.go(-1)
            },
            subimtAjax(){
                var _this =this;
                if(!_this.clickLoading) {
                    return false;
                }
                _this.$messagebox.confirm('是否确认提交','在线审批').then(function () {
                    console.log(_this.endTime - _this.startTime)
                    if(_this.typeOfLeave.nowType.id == 0){
                        _this.$toast({
                            message:"请选择请假类别",
                            duration:1500
                        });
                        return false;
                    }
                    if(_this.during.nowType.id == 0){
                        _this.$toast({
                            message:"请填写请假时长",
                            duration:1500
                        });
                        return false;
                    }
                    if(typeof _this.startTime != 'number' || typeof _this.endTime != 'number'){
                        _this.$toast({
                            message:"请选择申请时间",
                            duration:1500
                        });
                        return false;
                    }
                    if(_this.startTime > _this.endTime){
                        _this.$toast({
                            message:"开始时间应早于结束时间",
                            duration:1500
                        });
                        return false;
                    }
                    // if(_this.endTime - _this.startTime > _this.during.nowType.name * 24 * 3600){
                    //     _this.$toast({
                    //         message:"时间周期应小于请假时长",
                    //         duration:1500
                    //     });
                    //     return false;
                    // }
                    if(_this.approver.nowType.userid == 0){
                        _this.$toast({
                            message:"请选择审批人",
                            duration:1500
                        });
                        return false;
                    }
                    _this.clickLoading = false;
                    _this.$indicator.open({
                        text: '正在发布中',
                        spinnerType: 'triple-bounce'
                    });
                    var data = {
                        'class':_this.type,
                        'start_time':_this.startTime,
                        'end_time':_this.endTime,
                        'duration':_this.during.nowType.name,
                        'type':_this.typeOfLeave.nowType.id,
                        'agent':_this.agent,
                        'content':_this.remark
                    };
                    if(_this.id != 0) {
                        var url = '{:Url("Approval/edit")}';
                        data.id = _this.id;
                        var obj = {
                            'content': data,
                            'approval_user': _this.approver.nowType.userid,
                            'permission': _this.permission
                        }
                    } else {
                        var url = '{:Url("Approval/dayoff")}',
                            obj = data;
                        obj.approval_user = _this.approver.nowType.userid;
                    }
                    console.log(data)
                    _this.$http.post(url,obj,{emulateJSON:true}).then(function (res) {
                        var data = res.body;
                        console.log(data)
                        _this.$indicator.close();
                        if(data.code == 1){
                            _this.$toast({message:'提交成功',iconClass: 'icon', duration:1500});
                            window.sessionStorage.setItem('approval_type','2');
                            setTimeout(function () {
                                if(_this.id != 0) {
                                    window.location.replace('/home/approval/index.html');
                                    window.sessionStorage.setItem('approval_type','2');
                                } else {
                                    window.history.go(-1);
                                }
                            },500);
                        }else{
                            _this.clickLoading = true;
                            _this.$toast({
                                message: data.msg,
                                duration: 1500
                            });
                        }
                    }, function (res) {
                        _this.$indicator.close();
                        _this.$toast({
                            message: "提交失败，请重试！",
                            duration: 1500
                        });
                    });
                });

            }
        },
        filters: {
            daysFilter(value){
                console.log(value)
                return value
            }
        }
    })
</script>
{/block}
